<template>
	<view class="body">

		<swiper class="swiper" :circular="circular" :autoplay="false" :vertical="true"
			:disable-programmatic-animation="disableAnimation" :current="currentVideoIndex"
			@animationfinish="videoChangeAnimationFinish" @transition="transitionHandler">
			
			<swiper-item class="swiper-item" v-for="(item,index) in videoList" :key="index" :item-id="item.id">
				<view class="video-view">
					<video :id="'video_'+item.id" 
					:poster="item.cover_pic" 
					:src="item.video_url" 
					:controls="false" 
					object-fit="contain" 
					:muted="muted" 
					@ended="videoPlayEndHandler"
					@play="videoPlayHandler"
					@timeupdate="timeUpdateHandler"></video>
				</view>
				
				<view class="detail">
					<view v-if="item.extend.enable_link == 1" class="link" @click="openUrl(item.extend.link)">
						<view>
							<image :src="item.extend.link_pic" style="width: 100rpx;height: 100rpx;"></image>
						</view>
						<view style="height:100rpx;display: flex;flex-direction: column;justify-content: space-between;margin-left: 20rpx;">
							<view v-line-clamp="2">{{item.extend.link_title}}</view>
							<view>{{item.extend.link_desc}}</view>
						</view>
					</view>
					
					<view v-line-clamp="1" style="font-size: 14pt;">{{item.title}}</view>
					
					<view style="font-size: 10pt;display: flex;justify-content: space-between;">
						<view>
							<text v-if="item.user_id>1">{{item.nickname}}</text>
							<text v-else="item.user_id">@兰亭臻选</text>
						</view>
						<view>{{formatTimeToStr(item.created_at)}}</view>
					</view>
				</view>
			
				<view class="reward-porgress" v-if="item.extend.reward" @click="showRewardDetail(item)">
					<u-circle-progress 
						active-color="#2979ff" 
						:percent="item.percent ? item.percent : 0"
						width="110" 
						border-width="5"  
						bg-color="rgba(0,0,0,.5)">
						<view style="color:#fff;text-align: center;">
							<view v-if="item.extend.reward_status == 0">
								<view style="font-size: 10pt;font-weight: 600;">{{item.extend.reward_num}}</view>
								<view style="font-size: 8pt;">{{item.extend.reward_type == 'score' ? '积分' : '余额'}}</view>
							</view>
							<view v-else>
								<view style="font-size: 8pt;">已领</view>
							</view>
						</view>
					</u-circle-progress>
				</view>
				
			</swiper-item>

		</swiper>
		
		
		<u-popup v-model="rewardDetail.visible" mode="top" closeable @close="rewardDetailClose">
			<view style="height: 100vh;padding-top:100rpx;">
				<h3 style="text-align: center;padding-bottom: 40rpx;" v-line-clamp='1'>短视频观看奖励说明</h3>
				
				<view style="padding: 20rpx;font-weight: 600;">奖励领取信息：</view>
				<view v-if="rewardDetail.videoInfo" style="padding:0 50rpx;">
					<view class="reward-detail-row">
						<view>奖励类型</view>
						<view>{{rewardDetail.videoInfo.extend.reward_type == 'score' ? '积分' : '余额'}}</view>
					</view>
					<view class="reward-detail-row">
						<view>奖励数量</view>
						<view>{{rewardDetail.videoInfo.extend.reward_num}}</view>
					</view>
					<view class="reward-detail-row">
						<view>领取条件</view>
						<view>{{rewardDetail.videoInfo.extend.condition == 1 ? '播放成功' : '播放完成'}}</view>
					</view>
				</view>

				
				<view style="padding: 20rpx;">注：奖励会在达成领取条件后的5分钟内进行发放！</view>
				
				<view style="padding: 20rpx;font-weight: 600;text-align: center;">本活动所有解释权归兰亭臻选所有！</view>
			</view>
		</u-popup>
		
	</view>
</template>

<script>
	import {formatTimeToStr} from "@/utils/date";
	export default{
		data(){
			return {
				config:{
					enable:0,
					condition:2,
				},
				
				videoList:[],
				pagination:{
					current_page:1,
					total_count:0
				},
				
				currentVideoId:'',
				currentVideoIndex:0,
				sliderType:1,//1-往下翻，看下一个，2-往上翻，看上一个
				transitionData:[],
				disableAnimation:false,
				
				circular:false,
				muted:true,
				
				
				playingVideoId:"",
				playingVideoPercent:0,
				
				
				rewardDetail:{
					visible:false,
					videoInfo:''
				},
				
				queryVideoId:''
			}
		},
		async onLoad(opt) {
			this.queryVideoId = opt.video_id ?? '';
			let res = await this.$http.request({
				url: this.$api.short_video.getConfig,
				method: 'get',
			});
			if(res.code !== 0){
				return this.$http.toast(res.msg);
			}
			Object.assign(this.config,res.data);
			if( this.config.enable === 0 ){
				return uni.showModal({
					title:"温馨提示",
					content:"短视频应用已关闭，请稍后再尝试~",
					showCancel:false,
					success: function (res) {
						if (res.confirm) {
							uni.navigateTo({url:'/pages/index/index'});
						}
					}
				})
			}

			this.getInitVideoList();
		},
		methods:{

			//从后端加载一个视频
			async getVideo(id=0,type=1){
				let self = this;
				uni.showLoading({title:'加载中..'})
				let res = await self.$http.request({
					url: self.$api.short_video.getNextVideo,
					method: 'POST',
					data:{id,type},
				});
				if(res.code !== 0){
					uni.hideLoading()
					return self.$http.toast(res.msg);
				}
				if(res.data.length <= 0){
					uni.hideLoading()
					return self.$http.toast("没有更多了...");
				}
				if(type == 1){
					this.videoList.push(...res.data);
				}else{
					this.videoList.unshift(...res.data);
					this.currentVideoIndex++;
				}

				uni.hideLoading()
			},
			
			
			swiperChangeHandler(e){
				console.log('change',e.detail.current,e.detail.currentItemId)
				//先暂停当前正在播放的视频
				uni.createVideoContext(this.playingVideoId).pause();
				uni.createVideoContext(this.playingVideoId).seek(0);
				//将当前视图展示的视频ID赋值。
				this.playingVideoId = 'video_' + e.detail.currentItemId;
				//重新播放视频
				uni.createVideoContext(this.playingVideoId).play();
			},
			
			//滑动动画结束时的回调处理
			videoChangeAnimationFinish(e){
				
				this.currentVideoIndex = e.detail.current;
				let length = this.transitionData.length;
				let max = this.transitionData[length-1];
				this.transitionData = [];
				//滑动偏移值过小时，不做处理
				if( length <= 10 || Math.abs(max) < 80){
					return ;
				}
				this.sliderType = max > 0 ? 1 : 2;
				
				//先暂停当前正在播放的视频
				uni.createVideoContext(this.playingVideoId).pause();
				uni.createVideoContext(this.playingVideoId).seek(0);
				//将当前视图展示的视频ID赋值。
				this.playingVideoId = 'video_'+e.detail.currentItemId;
				//重新播放视频
				uni.createVideoContext(this.playingVideoId).play();

				if(e.detail.current == 0 || e.detail.current >= (this.videoList.length - 1)){
					this.getVideo(e.detail.currentItemId,this.sliderType);
				}
			},
			
			//swiper 内容滑动时的回调处理
			transitionHandler(e){
				
				let length = this.transitionData.length;
				//获取最后一个数
				let num = length > 0 ? this.transitionData[length-1] : 0;
				
				//限制记录数据数量上限，和排除抖动的数据。
				if(length < 99 && Math.abs(parseInt(e.detail.dy)) > Math.abs(num) ){
					this.transitionData.push(parseInt(e.detail.dy));
				}

			},

			//初始化时，加载多个视频数据
			async getInitVideoList(){
				let self = this;
				let res = await self.$http.request({
					url: self.$api.short_video.getInitVideo,
					method: 'POST',
					data:{page:self.pagination.current_page,id:this.queryVideoId},
					showLoading:true
				});
				uni.hideLoading()
				if(res.code !== 0){
					return self.$http.toast(res.msg);
				}
				if(res.data.length <= 0){
					uni.showModal({
						title: '温馨提示',
						content: '暂无短视频，敬请期待~',
						showCancel:false,
						confirmText:'返回',
						success: function (res) {
							if (res.confirm) {
								uni.navigateTo({url:'/pages/user/index'})
							}
						}
					});
					return ;
				}
				
				self.videoList.push(...res.data);
				self.currentVideoIndex = self.videoList.findIndex(item =>{
					return item.id == self.queryVideoId
				})

				setTimeout(function(){
					self.playingVideoId = 'video_' + self.videoList[self.currentVideoIndex].id;
					uni.createVideoContext(self.playingVideoId).play();
					uni.showModal({
						title: '温馨提示',
						content: '当前为静音模式播放，请先关闭静音模式。',
						// cancelText:'保持静音',
						showCancel:false,
						confirmText:'确认',
						success: function (res) {
							if (res.confirm) {
								self.muted = false;
								uni.createVideoContext(self.playingVideoId).play();
							}
						}
					});
				},100)
			},

			
			//视频播放的时长信息处理
			timeUpdateHandler(e){
				let cur = e.detail.currentTime;
				let total = e.detail.duration;
				let ratio = Math.round(cur / total * 100);
				this.videoList[this.currentVideoIndex].percent = ratio;
				this.$forceUpdate()
			},
			
			
			async videoPlayEndHandler(e){
				if(this.config.condition != 2){
					return ;
				}
				let videoId = e.target.id;
				let id = videoId.split('_')[1];
				let self = this;
				if(self.videoList[self.currentVideoIndex].id == id){
					if(this.config.reward_limit == 1 && self.videoList[self.currentVideoIndex].extend.reward_status){
						return ;
					}
					let res = await self.$http.request({
						url: self.$api.short_video.videoReward,
						method: 'POST',
						data:{video_id:id},
						showLoading:true
					});
					if(res.code == 0){
						self.videoList[self.currentVideoIndex].extend.reward_status = 1;
					}
				}
			},
			
			async videoPlayHandler(e){
				if(this.config.condition != 1){
					return ;
				}
				
				let videoId = e.target.id;
				let id = videoId.split('_')[1];
				let self = this;
				if(self.videoList[self.currentVideoIndex].id == id){
					if(this.config.reward_limit == 1 && self.videoList[self.currentVideoIndex].extend.reward_status){
						return ;
					}
					let res = await self.$http.request({
						url: self.$api.short_video.videoReward,
						method: 'POST',
						data:{video_id:id},
						showLoading:true
					});
					if(res.code == 0){
						self.videoList[self.currentVideoIndex].extend.reward_status = 1;
					}
				}
			},
			
			resetData(){
				this.videoList = [];
				this.pagination = {
					current_page:1,
					total_count:0
				};
			},

			openUrl(url){
				const regex = /^https?:\/\//;
				if(regex.test(url)){
					window.location.href = url;
				}else{
					uni.navigateTo({url})
				}
			},

			showRewardDetail(row){
				this.rewardDetail.videoInfo = row;
				this.rewardDetail.visible = true;
			},
			rewardDetailClose(){
				this.rewardDetail.videoInfo = '';
				this.rewardDetail.visible = false;
			}

		},
		computed:{
			formatTimeToStr(){
				return value => formatTimeToStr(value * 1000,'yyyy-MM-dd hh:mm')
			}
		},
	}
</script>

<style lang="scss">
	.body{
		width:100vw;
		height: 100vh;
		background-color: #000000;
		overflow: hidden;
		position: relative;
	}
	
	.swiper{
		width: 100vw;
		height: 100vh;
		z-index: 7
	}
	
	.swiper-item{
		width: 100vw;
		height: 100vh;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
	}
	
	
		
	.video-view{
		height: 500px;
		flex-grow: 9;
	}
	.video-view video{
		// width: 100vw;
		// min-height: 80vh;
		width: 100%;
		height: 100%;
	}
	
	.detail{
		min-height: 300rpx;
		color:#ffffff;
		padding: 0rpx 20rpx 30rpx;
		display:flex;
		flex-direction: column;
		justify-content: flex-end;
	}
	
	.link{
		color:#000;
		background-color: #fff;
		margin: 10rpx;
		padding: 10rpx;
		border-radius: 20rpx;
		display: flex;
		align-items: center;
	}
	
	
	.reward-porgress{
		position: fixed; 
		top:50rpx;
		right: 50rpx;
		z-index: 99;
		border-radius: 50%;
		overflow: hidden;
	}
	.reward-detail-row{
		display: flex;
		justify-content: space-between;
		border-bottom: 1rpx solid #f2f2f2;
		padding: 20rpx 0;
	}
</style>